package com.cnsuning.jobtool.utils;

import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CaculateTableDbno {
    @Test
    public void caculate() throws IOException {
        File file = new File("src/main/java/com/cnsuning/jobtool/utils/ROUTE_ORDER_ID.TXT");
        List<String> routeOrderIdList = FileUtils.readLines(file);
        Map<String,Map<String,List<String>>> map = new HashMap<>();
        String TABLENAME = "SO_FACTORY_ORDER_RET_CHG_APPLY";
        String DBNAME = "omsd";
        for (String routeOrderId : routeOrderIdList)
        {
            //计算库号
            long routeOrderIdNum = Long.parseLong(routeOrderId);
            long dbIndex = routeOrderIdNum % 32 + 65;
            String dbNo = DBNAME+"_"+String.format("%03d", dbIndex);
            //计算表号
            long tableIndex = routeOrderIdNum % 1024;
            String tableNo = TABLENAME+"_" + String.format("%04d", tableIndex);
            Map<String, List<String>> tableMap = map.get(dbNo);
            if (tableMap == null)
            {
                tableMap = new HashMap<>();
            }
            List<String> routeOrderIdMapList = tableMap.get(tableNo);
            if (routeOrderIdMapList == null)
            {
                routeOrderIdMapList = new ArrayList<>();
            }
            routeOrderIdMapList.add(routeOrderId);
            tableMap.put(tableNo,routeOrderIdMapList);
            map.put(dbNo,tableMap);
            System.out.println("dbNo:" + dbNo + ",tableNo:" + tableNo+",routeOrderId:" + routeOrderId);
        }
        String SQL_TEMPLATE = "select * from %s where ROUTE_ORDER_ID in(%s)|%s";
        for (Map.Entry<String,Map<String,List<String>>> entry : map.entrySet())
        {
            String dbName = entry.getKey();
            Map<String, List<String>> tableMap = entry.getValue();
            for (Map.Entry<String, List<String>> tableEntry : tableMap.entrySet())
            {
                String subTableName = tableEntry.getKey();
                List<String> subTableRouteOrderIdList = tableEntry.getValue();
                String routeOrderIdInStr = "";
                for (String routeOrderId : subTableRouteOrderIdList)
                {
                    routeOrderIdInStr +=","+"'"+routeOrderId+"'";
                }
                routeOrderIdInStr = routeOrderIdInStr.substring(1);
                System.out.println(String.format(SQL_TEMPLATE,subTableName,routeOrderIdInStr,dbName));
            }
        }
//        System.out.println(map);
    }
}
